const db = require("../dbs/db");
const jwt = require("jsonwebtoken")

class Hero_Controller {
    static async create(ctx, next) {
        const token = String(ctx.request.headers.authorization || '').split(' ').pop()
        if (!token) {
            ctx.response.status = 401;
            ctx.body = {
                code: 401,
                msg: '请先登录',
            }
            return
        }
        const { id } = jwt.verify(token, 'glory-of-kings')
        if (!id) {
            ctx.response.status = 401;
            ctx.body = {
                code: 401,
                msg: '请先登录',
            }
            return
        }
        ctx.req.user = await db.AdminUser.findOne({
            where: { id: id }
        })
        if (!ctx.req.user) {
            ctx.response.status = 401;
            ctx.body = {
                code: 401,
                msg: '请先登录',
            }
            return
        }
        await next()
        //接收客服端
        let req = ctx.request.body;
        if (req.name && req.avatar && req.title && req.score && req.type) {
            try {
                await db.Score.create({
                    difficult: req.score.difficult,
                    skills: req.score.skills,
                    attack: req.score.attack,
                    survival: req.score.survival,
                });
                await db.Tips.create({
                    usageTips: req.tip.usageTips,
                    battleTips: req.tip.battleTips,
                    teamTips: req.tip.teamTips,
                });


                let scoreID = await db.Score.findOne({
                    where: {
                        difficult: req.score.difficult,
                        skills: req.score.skills,
                        attack: req.score.attack,
                        survival: req.score.survival,
                    }
                })
                let tipsID = await db.Tips.findOne({
                    where: {
                        usageTips: req.tip.usageTips,
                        battleTips: req.tip.battleTips,
                        teamTips: req.tip.teamTips,
                    }
                })

                const ret = await db.Hero.create({
                    name: req.name,
                    avatar: req.avatar,
                    bgc: req.bgc,
                    title: req.title,
                    score_id: scoreID.id,
                    tips_id: tipsID.id,
                });

                const data = await db.Hero.findOne({
                    where: { name: ret.name }
                })
                for (let i = 0; i < req.cooperates.length; i++) {
                    await db.Cooperate.create({
                        hero: req.cooperates[i].hero,
                        description: req.cooperates[i].description,
                        heroId: data.id
                    });
                }
                for (let i = 0; i < req.skills.length; i++) {
                    await db.Skill.create({
                        name: req.skills[i].name,
                        icon: req.skills[i].icon,
                        delay: req.skills[i].delay,
                        cost: req.skills[i].cost,
                        description: req.skills[i].description,
                        tips: req.skills[i].tips,
                        heroId: data.id
                    });
                }
                for (let i = 0; i < req.type.length; i++) {
                    await db.SecHero.create({
                        secid: req.type[i],
                        heroid: data.id
                    })
                }
                for (let i = 0; i < req.heroitem.length; i++) {
                    await db.HeroItem.create({
                        itemid: req.heroitem[i],
                        heroid: data.id
                    })
                }
                ctx.response.status = 200;
                ctx.body = {
                    code: 200,
                    msg: '创建成功',
                    data
                }
            } catch (err) {
                ctx.response.status = 412;
                ctx.body = {
                    code: 412,
                    msg: '创建失败',
                    data: err
                }
            }
        } else {
            ctx.response.status = 416;
            ctx.body = {
                code: 200,
                msg: '参数不齐全'
            }
        }
    }

    static async detail(ctx, next) {
        const token = String(ctx.request.headers.authorization || '').split(' ').pop()
        if (!token) {
            ctx.response.status = 401;
            ctx.body = {
                code: 401,
                msg: '请先登录',
            }
            return
        }
        const { id } = jwt.verify(token, 'glory-of-kings')
        if (!id) {
            ctx.response.status = 401;
            ctx.body = {
                code: 401,
                msg: '请先登录',
            }
            return
        }
        ctx.req.user = await db.AdminUser.findOne({
            where: { id: id }
        })
        if (!ctx.req.user) {
            ctx.response.status = 401;
            ctx.body = {
                code: 401,
                msg: '请先登录',
            }
            return
        }
        await next()
        let cid = ctx.params.id;
        if (cid) {
            try {
                // 查询详情模型
                let data = await db.Hero.findOne({
                    where: { id: cid }, include: [{
                        model: db.Score
                    }, {
                        model: db.Tips
                    }, {
                        model: db.Cooperate
                    }, {
                        model: db.Skill
                    }]
                })
                ctx.response.status = 200;
                ctx.body = {
                    code: 200,
                    msg: '查询成功',
                    data,
                }
            } catch (err) {
                ctx.response.status = 412;
                ctx.body = {
                    code: 412,
                    msg: '查询失败',
                    data
                }
            }
        } else {
            ctx.response.status = 416;
            ctx.body = {
                code: 416,
                msg: 'ID必须传'
            }
        }
    }

    static async update(ctx, next) {
        const token = String(ctx.request.headers.authorization || '').split(' ').pop()
        if (!token) {
            ctx.response.status = 401;
            ctx.body = {
                code: 401,
                msg: '请先登录',
            }
            return
        }
        const { id } = jwt.verify(token, 'glory-of-kings')
        if (!id) {
            ctx.response.status = 401;
            ctx.body = {
                code: 401,
                msg: '请先登录',
            }
            return
        }
        ctx.req.user = await db.AdminUser.findOne({
            where: { id: id }
        })
        if (!ctx.req.user) {
            ctx.response.status = 401;
            ctx.body = {
                code: 401,
                msg: '请先登录',
            }
            return
        }
        await next()
        let req = ctx.request.body;
        let cid = ctx.params.id;
        if (cid) {
            try {
                let model = await db.Hero.findOne({
                    where: { id: cid }
                })

                await db.Score.update({
                    difficult: req.score.difficult,
                    skills: req.score.skills,
                    attack: req.score.attack,
                    survival: req.score.survival,
                }, { where: { id: req.score_id } })


                await db.Tips.update({
                    usageTips: req.tip.usageTips,
                    battleTips: req.tip.battleTips,
                    teamTips: req.tip.teamTips,
                }, { where: { id: req.tips_id } })

                await db.Cooperate.destroy({
                    where: {
                        heroId: cid
                    }
                })

                for (let i = 0; i < req.cooperates.length; i++) {
                    await db.Cooperate.create({
                        hero: req.cooperates[i].hero,
                        description: req.cooperates[i].description,
                        heroId: cid
                    });
                }

                await db.Skill.destroy({
                    where: {
                        heroId: cid
                    }
                })
                for (let i = 0; i < req.skills.length; i++) {
                    await db.Skill.create({
                        name: req.skills[i].name,
                        icon: req.skills[i].icon,
                        delay: req.skills[i].delay,
                        cost: req.skills[i].cost,
                        description: req.skills[i].description,
                        tips: req.skills[i].tips,
                        heroId: cid
                    });
                }

                await db.SecHero.destroy({
                    where: {
                        heroid: cid
                    }
                })
                for (let i = 0; i < req.type.length; i++) {
                    await db.SecHero.create({
                        secid: req.type[i],
                        heroid: cid
                    })
                }

                await db.HeroItem.destroy({
                    where: {
                        heroid: cid
                    }
                })
                for (let i = 0; i < req.heroitem.length; i++) {
                    await db.HeroItem.create({
                        itemid: req.heroitem[i],
                        heroid: cid
                    })
                }
                if (model.name != req.name || model.avatar != req.avatar || model.title != req.title) {
                    await db.Hero.update({ name: req.name, avatar: req.avatar, bgc: req.bgc, title: req.title }, { where: { id: cid } })
                }
                let data = await db.Hero.findOne({
                    where: {
                        name: req.name,
                    }
                })
                ctx.response.status = 200;
                ctx.body = {
                    code: 200,
                    msg: '更新成功',
                    data
                }
            } catch (err) {
                ctx.response.status = 412;
                ctx.body = {
                    code: 412,
                    msg: '更新失败',
                }
            }
        } else {
            ctx.response.status = 416;
            ctx.body = {
                code: 416,
                msg: '缺少ID值或name值'
            }
        }
    }

    static async delete(ctx, next) {
        const token = String(ctx.request.headers.authorization || '').split(' ').pop()
        if (!token) {
            ctx.response.status = 401;
            ctx.body = {
                code: 401,
                msg: '请先登录',
            }
            return
        }
        const { id } = jwt.verify(token, 'glory-of-kings')
        if (!id) {
            ctx.response.status = 401;
            ctx.body = {
                code: 401,
                msg: '请先登录',
            }
            return
        }
        ctx.req.user = await db.AdminUser.findOne({
            where: { id: id }
        })
        if (!ctx.req.user) {
            ctx.response.status = 401;
            ctx.body = {
                code: 401,
                msg: '请先登录',
            }
            return
        }
        await next()
        let cid = ctx.params.id;
        try {
            let data = await db.Hero.findOne({
                where: { id: cid }
            })
            await db.Cooperate.destroy({
                where: {
                    heroId: cid
                }
            })
            await db.Skill.destroy({
                where: {
                    heroId: cid
                }
            })
            await db.Hero.destroy({
                where: {
                    id: cid
                }
            })

            await db.Score.destroy({
                where: {
                    id: data.score_id
                }
            })
            await db.Tips.destroy({
                where: {
                    id: data.tips_id
                }
            })

            ctx.response.status = 200;
            ctx.body = {
                code: 200,
                msg: `删除${data.name}成功`,
            }
        } catch (err) {
            ctx.response.status = 412;
            ctx.body = {
                code: 412,
                msg: '删除失败',
            }
        }
    }

    static async list(ctx) {
        let data = await db.Hero.findAll(
            {
                include: [{
                    model: db.SecCategory,
                    attributes: ['name']
                },
                {
                    model: db.Item,
                    through: {
                        model: db.HeroItem
                    }
                },
                {
                    model: db.Score,
                    attributes: ['difficult', 'skills', 'attack', 'survival']
                },
                {
                    model: db.Tips,
                    attributes: ['usageTips', 'battleTips', 'teamTips']
                },
                {
                    model: db.Cooperate,
                    attribute: ['hero', 'desciption']
                },
                {
                    model: db.Skill,
                    attribute: ['name', 'icon', 'delay', 'cost', 'desciption', 'tips']
                }
                ],
            }
        )
        ctx.response.status = 200;
        ctx.body = {
            code: 200,
            msg: '查询成功',
            data
        }
    }
}

module.exports = Hero_Controller;